package fintecher.com.service.impl;

import fintecher.com.bean.Upload;
import fintecher.com.dao.UploadMapper;
import fintecher.com.exception.FileNameLengthLimitExceededException;
import fintecher.com.exception.InvalidExtensionException;
import fintecher.com.service.IAttachmentService;
import fintecher.com.util.FileUploadUtils;
import fintecher.com.util.IpUtils;
import fintecher.com.util.SftpUtils;
import fintecher.com.util.StringUtils;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

//@Transactional
@Service("attachmentService")
public class AttachmentServiceImpl  implements IAttachmentService {
	@Value("${upload_size}")
	private long maxSize;
	@Value("${upload_dir}")
	private String baseDir;
	@Value("${upload_extension}")
	private  String extension;
	private boolean needDatePathAndRandomName = true;
	private String[] allowedExtension;

	@Autowired
	private SftpUtils sftpUtils;

	@Autowired
	private UploadMapper uploadMapper;

	@Override
	public Upload upload(HttpServletRequest request, MultipartFile file,Upload uploadEntity) throws FileSizeLimitExceededException, InvalidExtensionException, FileNameLengthLimitExceededException, IOException {
		allowedExtension = extension.split(",");
		String url = FileUploadUtils.upload(request, baseDir, file, allowedExtension, maxSize, needDatePathAndRandomName);
		String filename = file.getOriginalFilename();
		Long size = file.getSize();
		String realFileName = StringUtils.getFileNameNoEx(filename);
		String fileext = StringUtils.getExtensionName(filename);
		// 保存上传的信息
		Upload attachment = new Upload();
		attachment.setFileext(fileext);
		attachment.setFilename(realFileName);
		attachment.setFilepath(url);
		attachment.setFilesize(size.intValue());
		attachment.setStatus("1");
		attachment.setUploadip(IpUtils.getIpAddr(request));
		attachment.setUploadtime(new Date());
		attachment.setUserid(uploadEntity.getUserid());  //用户id
		attachment.setDelFlag("0");
		attachment.setUrl(uploadEntity.getUrl());
		attachment.setReferId(uploadEntity.getReferId());
		uploadMapper.insert(attachment);
		return attachment;
	}



}
